const User = require('../models/users'); // 引入数据模型
const Token= require('../utils/token');

class UserController {
  constructor() {
  }

  async register(){
    try {
      return new Promise((resolve, reject) => {
        User.findAll().then(rows=>{
          resolve(rows);
        })
      });
    } catch (error) {
      console.log('console_2024年07月12日 14时41分36秒：', error);
    }
  }

  //登录
  async login(username, password) {
    try {
      return new Promise((resolve, reject) => {
        User.findOne({ where:{username,password}}).then(res => {
          const user = res&&res.dataValues;
          if(!user) {
            resolve({code: 401, msg: '用户名或密码错误'});
          }else{
            const token =new Token().createToken(user);
            resolve({code: 200, msg: '登录成功', token});
          }
        })
      });
    } catch (error) {
      console.log('console_2024年07月12日 14时41分36秒：', error);
    }
  }

  //分页获取用户
  async getUsers(page=1,pageSize=10) {
    const offset = (page - 1) * pageSize;
    const limit = pageSize;

    try {
        const [users, totalCount] = await Promise.all([
            User.findAll({
                offset: offset,
                limit: limit
            }),
            User.count()
        ]);
        return {
            rows: users,
            total: totalCount,
            current: page
        };
    } catch (error) {
        console.error('Error fetching users:', error);
        throw error;
    }
  }

  async addUser(user){
    try {
      const newUser = await User.create(user);
      return newUser;
    } catch (error) {
        console.error('Error creating user:', error);
        throw error;
    }
  }
}
module.exports = UserController
